package com.school_admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.school_admin.config.JwtUtil;
import com.school_admin.config.Result;
import com.school_admin.entity.Post;
import com.school_admin.entity.User;
import com.school_admin.mapper.PostMapper;
import com.school_admin.mapper.UserMapper;
import com.school_admin.service.impl.UserServiceImpl;
import com.school_admin.util.CreateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author
 * @since 2024-03-18
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private CreateTime createTime;
    @Autowired
    private JwtUtil jwtUtil;

    // 使用 restfull风格api
    // 查询所有
    @GetMapping("list")
    public Result<?> getUserList() {
        return Result.success("查询所有用户");
    }

    // 添加 / 注册用户
    @PostMapping("add")
    public Result<String> addUser(User user) {
        /*
         *   TODO 1. 判断是否存在该用户
         *   TODO 2. 添加用户
         *   TODO 3. 返回结果
         * */

        // TODO 1
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        User one = userService.getOne(wrapper);
        if (one != null) {
            return Result.fail("用户已存在");
        }
        // TODO 2
        String avatar = "http://localhost:8081/static/image/default.webp";
        user.setAvatar(avatar);
        user.setTime(createTime.getTime());
        userService.save(user);
        // TODO 3
        return Result.success("用户注册成功");
    }

    // TODO 删除
    @DeleteMapping("delete/{uid}")
    public Result<String> deleteUser(@PathVariable String uid) {
        boolean is = userService.removeById(uid);
        // 返回结果
        if (is) {
            return Result.success("删除用户成功");
        }
        return Result.success("删除用户");
    }

    // TODO 保存用户信息
    @PutMapping("saveInfo")
    public Result<String> updateUser(User user) {
        boolean is = userService.updateById(user);
        if (is) {
            return Result.success("保存信息成功");
        }
        return Result.fail("保存信息失败");
    }

    // TODO 登录
    @PostMapping("login")
    public Result<?> login(User user) {
        /*
            TODO 1. 判断用户名是否存在
            TODO 2. 判断密码是否正确
            TODO 3. 验证用户是否被封禁
            TODO 4. 返回结果
         */
        // TODO 1
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, user.getUsername());
        User one = userMapper.selectOne(wrapper);
        if (one == null) {
            return Result.fail("用户不存在");
        }
        // TODO 2
        if (!one.getPassword().equals(user.getPassword())) {
            return Result.fail("密码错误");
        }
        // TODO 3
        wrapper.eq(User::getStatus,  1);
        Long count = userMapper.selectCount(wrapper);
        if (count > 0) {
            return Result.fail("该用户已被封禁");
        }
        // TODO 4
        // 登录成功，生成token
        String token = jwtUtil.createToken(one);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("uid", one.getUid());
        map.put("role", one.getRole());
        map.put("avatar", one.getAvatar());
        map.put("username", one.getUsername());
        return Result.success(map, "登录成功");
    }

    // TODO 查询单个用户
    @GetMapping("find/{uid}")
    public Result<User> getUser(@PathVariable String uid) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUid, uid);
        User user = userMapper.selectOne(wrapper);
        return Result.success(user);
    }

    // TODO 查询获赞 ，收藏数
    @GetMapping("getCount")
    public Result<Map<String, Integer>> getCount(String uid) {
        return userService.getCount(uid);
    }

    // TODO 修改用户状态 [封禁用户]
    @PutMapping("updateStatus/{uid}/{status}")
    public Result<String> updateStatus(@PathVariable String uid, @PathVariable Integer status) {
        User user = new User();
        user.setUid(uid);
        user.setStatus(status == 1 ? 0 : 1);
        int is = userMapper.updateById(user);
        if (is == 0) {
            return Result.fail("状态更新失败");
        }
        return Result.success("状态更新成功");
    }

    // TODO 获取用户收藏列表
    @GetMapping("findMyFavorites")
    public Result<?> findMyFavorites(
            int page,
            int pageSize,
            String uid) {
        return userService.getUserCollectionList(page, pageSize, uid);
    }

    // TODO 获取用户发布列表
    @GetMapping("findMyRelease")
    public Result<?> findMyRelease(String uid, int page, int pageSize) {
        int start = (page - 1) * pageSize;
        Map<String, Object> map = new HashMap<>();
        List<Post> list = userMapper.getUserReleaseList(uid, start, pageSize);
        if (list.size() > 0) {
            map.put("list", list);
            map.put("total", userMapper.getUserReleaseCount(uid));
            return Result.success(map);
        }
        return Result.success("未发布");
    }

    // TODO 用户修改密码
    @PutMapping("updatePassword")
    public Result<String> updatePassword(String oldPassword, String newPassword,
                                         String uid) {
        User user = new User();
        // 获取当前用户
        User one = userService.getById(uid);
        // 判断原密码
        if (!one.getPassword().equals(oldPassword)) {
            return Result.fail("原密码错误");
        }
        // 修改密码
        user.setUid(uid);
        user.setPassword(newPassword);
        // 更新到数据库
        boolean is = userService.updateById(user);
        if (is) {
            return Result.success("修改密码成功");
        }
        return Result.fail("修改密码失败");
    }


    // TODO 获取用户列表
    @GetMapping("getUserList")
    public Result<Map> getUserList(int page, int pageSize, String username,String role,
                                   String uid) {
        // TODO 搜索用户
        if (username == null || username.equals("")) {
            username = "";
            return userService.getUserList(page, pageSize,role,uid);
        } else {
            return userService.searchUser(page, pageSize, username,role,uid);
        }
    }
    // 设为管理员
    @PutMapping("setAdmin/{uid}/{role}")
    public Result<String> setAdmin(@PathVariable String uid,@PathVariable String role) {
        User user = new User();
        user.setUid(uid);
        user.setRole(role);
        boolean is = userService.updateById(user);
        if (is) {
            return Result.success("操作成功");
        }
        return Result.fail("操作失败");
    }

    // TODO 获取管理员列表
//    @GetMapping("getAdminList")
//    public Result<?> getAdminList(int page, int pageSize, String username) {
//        if (username == null || username.equals("")) {
//            username = "";
//            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(User::getRole, "R");
//            Page<User> pageInfo = new Page<>(page, pageSize);
//            IPage<User> userIPage = userService.page(pageInfo, wrapper);
//            if (userIPage.getTotal() > 0) {
//                Map<String,Object> map = new HashMap<>();
//                map.put("total",userIPage.getTotal());
//                map.put("list",userIPage.getRecords());
//                return Result.success(map);
//            }
//            return Result.success("管理员列表为空");
//        } else {
//           // 搜索管理员
//            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(User::getRole, "R").like(User::getUsername, username);
//            Page<User> pageInfo = new Page<>(page, pageSize);
//            IPage<User> userIPage = userService.page(pageInfo, wrapper);
//            if (userIPage.getTotal() > 0) {
//                Map<String,Object> map = new HashMap<>();
//                map.put("total",userIPage.getTotal());
//                map.put("list",userIPage.getRecords());
//                return Result.success(map);
//            }
//            return Result.success("未搜索出该用户");
//        }
//    }
}
